package com.mach.platform.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.mach.platform.domain.AlarmMessage;
import com.mach.platform.repository.AlarmMessageRepo;
import com.mach.platform.utils.springdata.DynamicSpecifications;
import com.mach.platform.utils.springdata.SearchFilter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.List;
import java.util.Map;

/**
 * 报警业务类
 */

@Service
public class AlarmMessageServiceImpl implements BaseService<AlarmMessage>{

    private static final DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd[['T'hh][:mm][:ss]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
            .toFormatter();

    private static final DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd[['T'hh][:mm][:ss]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 23)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 59)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 59)
            .parseDefaulting(ChronoField.MILLI_OF_SECOND, 999)
            .toFormatter();
    private static boolean IS_RUN_ALARM = true;

    @Autowired
    private AlarmMessageRepo alarmMessageRepo;

    @Autowired
    private ExportFileServiceImpl exportFileService;

    //报警
    @Autowired
    private AlarmServiceImpl alarmService;


    /**
     * 执行报警信息判断
     */
    public void alarmPreset(){
        while (IS_RUN_ALARM) {
            alarmService.init();
        }
    }

    @Override
    public AlarmMessage save(AlarmMessage alarmMessage) {
        if (ObjectUtils.allNotNull(alarmMessage)){
            return alarmMessageRepo.save(alarmMessage);
        }
        return null;
    }

    @Override
    public List<AlarmMessage> insertObjInBatch(List<AlarmMessage> list) {
        return null;
    }

    @Override
    public AlarmMessage update(AlarmMessage alarmMessage) {
        if (ObjectUtils.allNotNull(alarmMessage)){
            alarmMessage.setIsOperation(1);
        }
        return this.save(alarmMessage);
    }

    @Override
    public int delete(Long[] ids) {
        return 0;
    }

    public void downloadTable(Sort sort, Map params, HttpServletResponse response) {
        Specification specification = getSpecification(params);
        List<AlarmMessage> resultList = alarmMessageRepo.findAll(specification, sort);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("母线温度监控数据", "母排"),
                AlarmMessage.class, resultList);
        String fileName = "母线测温数据" + ".xls";
        exportFileService.downloadFile(response, workbook, fileName);
    }

    @Override
    public Page<AlarmMessage> list(Pageable pageable, Map params) {
        Specification specification = getSpecification(params);
        Page<AlarmMessage> result = alarmMessageRepo.findAll(specification, pageable);
        return result;
    }

    private Specification getSpecification(Map params) {
        if (MapUtils.isNotEmpty(params)) {
            Object workshopId = params.get("workshopId");
            Object fuzzySearch = params.get("fuzzySearch");
            Object alarmClassify = params.get("alarmClassify");
            Object isOperation = params.get("isOperation");
            Object startTime = params.get("startTime");
            Object endTime = params.get("endTime");


            if (ObjectUtils.allNotNull(workshopId) && StringUtils.isNotEmpty(workshopId.toString())) {
                params.put("workshopId_eq", workshopId.toString().trim());
                params.remove("workshopId");
            }
            if (ObjectUtils.allNotNull(fuzzySearch) && StringUtils.isNotEmpty(fuzzySearch.toString())) {
                params.put("busNumber_switchNumber_plike", fuzzySearch.toString().trim());
                params.remove("fuzzySearch");
            }
            if (ObjectUtils.allNotNull(alarmClassify) && StringUtils.isNotEmpty(alarmClassify.toString())) {
                params.put("alarmClassify_eq", alarmClassify.toString().trim());
                params.remove("alarmClassify");
            }
            if (ObjectUtils.allNotNull(isOperation) && StringUtils.isNotEmpty(isOperation.toString())) {
                params.put("isOperation_eq", isOperation.toString().trim());
                params.remove("isOperation");
            }
            if (ObjectUtils.allNotNull(startTime) && StringUtils.isNotEmpty(startTime.toString())) {
                params.put("alarmMessageTime_gte", LocalDateTime.parse(startTime.toString().trim(), formatter1));
                params.remove("startTime");
            }
            if (ObjectUtils.allNotNull(endTime) && StringUtils.isNotEmpty(endTime.toString())) {
                params.put("alarmMessageTime_lte", LocalDateTime.parse(endTime.toString().trim(), formatter2));
                params.remove("endTime");
            }

        }
        return DynamicSpecifications.bySearchFilter(SearchFilter.parse(params).values(), AlarmMessage.class);
    }

    @Override
    public AlarmMessage info(Long id) {
        return null;
    }

    public String update(Long id, String dealPeople, String dealResult) {
        int result = alarmMessageRepo.update(id, dealPeople, dealResult);
        return result > 0 ? "处理成功" : "处理失败";
    }

}
